<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button v-if="checkPermission('p-em-excel-export')" type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button v-if="checkPermission('p-em-excel-upload')" type="danger" size="small" @click="handleDownload()">excel导出</el-button>
          <el-button v-if="checkPermission('p-em-add')" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{row}">
              <img v-imgerror="img404" :src="row.staffPhoto||defaultImg" alt="" class="staff">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{ row }">
              {{ formateTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{ row }">
              <el-button v-if="checkPermission('p-em-look')" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button v-if="checkPermission('assign_role')" type="text" size="small" @click="assignRole(row.id)">分配角色</el-button>
              <el-button v-if="checkPermission('p-em-del')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="pageSize"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <add-employee :show-dialog.sync="showDialog" />
      <assign-role :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeListApi, delEmployeeApi } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import dayjs from 'dayjs'
import AddEmployee from './components/add-employee'
import assignRole from './components/assign-role.vue'
import permission from '@/mixins/permission'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    assignRole
  },
  mixins: [permission],
  data() {
    return {
      list: [],
      page: 1, // 当前页
      pageSize: 10, // 每页条数
      total: 0, // 总数
      loading: false,
      showDialog: false,
      defaultImg: 'https://x0.ifengimg.com/res/2020/D8D9696C819DB87223F28494DA47912F5C6B1A03_size101_w1920_h1080.jpeg',
      img404: 'https://ts1.cn.mm.bing.net/th/id/R-C.fa626b88e86ccce069944c476531f8fd?rik=K%2b%2fTxVp0fkgy8w&riu=http%3a%2f%2fpuyimed.com%2fen%2fimages%2f404.png&ehk=plBu7AMKgvXmYXLi5%2bDhvEv4bWhfv3uoglXP7xNnUFc%3d&risl=&pid=ImgRaw&r=0',
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    console.log(this.roles)

    this.getEmployeeList()
  },
  methods: {
    assignRole(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    async handleDownload() {
      const { data: { rows }} = await getEmployeeListApi(1, this.total)
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const list = this.formateDate(rows, headersArr, headersRelations)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // 表头 必填
          data: list, // 具体数据 必填
          filename: '员工信息', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    formateDate(rows, headersArr, headersRelations) {
      const list = []
      rows.forEach(item => {
        const tempArr = []
        headersArr.forEach(header => {
          const englishKey = headersRelations[header]
          // tempArr.push(item[englishKey])
          let value = item[englishKey]
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = this.formateTime(value)
          }
          if (englishKey === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(obj => obj.id === +value)
            value = obj ? obj.value : '未知'
          }
          tempArr.push(value)
        })
        list.push(tempArr)
      })
      return list
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    async getEmployeeList() {
      this.loading = true
      const { data } = await getEmployeeListApi(this.page, this.pageSize)
      const { total, rows } = data
      this.total = total
      this.list = rows
      this.loading = false
    },
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getEmployeeList()
    },
    delEmployee(id) {
      this.$confirm('你确定要删除改员工？', '温馨提示').then(async() => {
        await delEmployeeApi(id)
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success('删除成功')
        this.getEmployeeList()
      }).catch(() => {
        console.log('取消')
      })
    },
    formateTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    }
  }
}
</script>

<style scoped lang="scss">
.staff {
      width: 70px;
      height: 70px;
      border-radius: 50%;
    }
</style>
